<template>
  <el-form :model="person" :rules="rules" ref="person" label-width="100px" class="w-50">
    <el-form-item label="头像" prop="nick_name">
      <set-avatar ref="set" :img-url="person.avatar" @upload-success="setNewImg"></set-avatar>
    </el-form-item>
    <el-form-item label="昵称" prop="nick_name">
      <el-input v-model="person.nick_name"></el-input>
    </el-form-item>
    <el-form-item label="电话">
      <el-input v-model="person.phone"></el-input>
    </el-form-item>
    <el-form-item label="邮箱">
      <el-input v-model="person.email"></el-input>
    </el-form-item>
    <el-form-item label="自我介绍" prop="desc">
      <el-input type="textarea" v-model="person.self_introduction"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm">保存修改</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import SetAvatar from './SetAvatar'
import axios from 'axios'
export default {
  name: "person_index",
  title: "个人资料设置",
  data () {
    return {
      person: this.$store.state.user.user,
      rules: {
        nick_name: [{
            required: true,
            message: '请输入昵称',
            trigger: 'blur'
          },
          {
            min: 1,
            max: 15,
            message: '昵称长度在 1 到 15 个字符',
            trigger: 'blur'
          }
        ],
      }
    }
  },
  methods: {
    submitForm () {
      this.$refs.person.validate((valid) => {
        if (valid) {
          // 提交修改
          axios.post('modifyUser', this.$paramsConvert(this.person)).then(res => {
            if (res.data.status) {
              this.updateUser()
              this.$message({
                showClose: true,
                message: res.data.msg,
                type: 'success'
              })
            } else {
              this.$codeError(res)
            }
          }).catch(error => {
            this.$catchError(error)
          })
        }
      })
    },
    setNewImg (url) {
      if (this.person.avatar) { // 如果有值将之前得文件删掉，为啥，因为穷呗
        let key = this.person.avatar.split('/')[this.person.avatar.split('/').length - 1]
        axios.delete('/file/delete/' + key)
      }
      this.person.avatar = url
      axios.post('avatar', this.$paramsConvert({avatar: url})).then(res => {
        if (res.data.status) {
          this.updateUser()
          this.$message({
            showClose: true,
            message: res.data.msg,
            type: 'success'
          })
        } else {
          this.$codeError(res)
        }
      }).catch(error => {
        this.$catchError(error)
      })
    },
    updateUser () {
      let user = Object.assign({}, this.$store.state.user.user, this.person)
      this.$store.dispatch('setUser', Object.assign(this.$store.state.user, {user: user}))
    }
  },
  components: {
    SetAvatar
  }
}
</script>

<style lang="less">
</style>
